package com.huayi.gg.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;

import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;

import com.huayi.gg.R;
import com.huayi.gg.broadcast.ReceiverMsg;
import com.huayi.gg.config.API;
import com.huayi.gg.model.ServerBean;
import com.huayi.gg.service.IndexService;
import com.huayi.gg.utils.GlideImageLoader;
import com.huayi.gg.utils.HttpClient;
import com.huayi.gg.utils.MyUtil;
import com.huayi.gg.utils.Utils;
import com.xuexiang.xupdate.XUpdate;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class MainActivity extends Activity {
    private Context context;

    private Banner banner;

    private ImageView imageView;
    private LinearLayout llqr;
    private ImageView qr;
    private SharedPreferences sp;
    private TextView txtcode;
    private  LinearLayout lllogo;
    private String imgurl= "";
    private String code ="";
    private  String keys = "G19OWOqM0H1quFaZwUz9SHeZgNd7fr9R";
    private String BASE_PATH="";
    private String docName="";



    private  Intent intentImage=null;
    private  Intent intentVideo=null;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context= this;



        setContentView(R.layout.activity_main);
        initView();

        initData();
        registerReceiver();


        XUpdate.newBuild(this)
                .updateUrl(API.http+"/app/version")
                .isAutoMode(true)
                .update();




    }





    private void sgb() {
         String mac =  API.getDeviceId(this);

        // mac="1bcfff15724f4521";


        // Toast.makeText(MainActivity.this,mac,Toast.LENGTH_LONG).show();

        IndexService.getConfig(mHandler,mac,1);

        List list = new ArrayList<>();
        list.add(R.drawable.banner1);
        list.add(R.drawable.banner2);
        list.add(R.drawable.banner3);
        list.add(R.drawable.banner4);
        list.add(R.drawable.banner5);


        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(list);
        //banner设置方法全部调用完毕时最后调用
        banner.isAutoPlay(true);
        banner.setDelayTime(8000);
        banner.start();

        //增加点击事件
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {

            }
        });


    }

    //判断是否联网
    private boolean checkConnectNetwork(Context context) {

        ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        @SuppressLint("MissingPermission") NetworkInfo net = conn.getActiveNetworkInfo();
        if (net != null && net.isConnected()) {
            return true;
        }
        return false;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private  void  initData(){

        boolean y = checkConnectNetwork(this);
        if(y==false){
//            banner.setVisibility(View.GONE);
//            imageView.setImageDrawable(getDrawable(R.drawable.wuwangluo));
//            imageView.setVisibility(View.VISIBLE);
            Intent intent = new Intent(this,NoWifiActivity.class);

            startActivityForResult(intent,2);

        }else{
            banner.setVisibility(View.VISIBLE);
            imageView.setVisibility(View.GONE);
            sgb();
        }
    }



    private void  initView(){
        imageView= findViewById(R.id.imageView);

        sp = getSharedPreferences("cache", Context.MODE_PRIVATE);
        banner = findViewById(R.id.banner);
        txtcode =findViewById(R.id.txtcode);
        llqr = findViewById(R.id.llqr);
        qr = findViewById(R.id.qr);
        lllogo= findViewById(R.id.lllogo);


    }
    private void registerReceiver(){

        try {
            IntentFilter filter1 = new IntentFilter();
            filter1.addAction(ReceiverMsg.message);
            filter1.addAction(ReceiverMsg.rotate);
            filter1.addAction(ReceiverMsg.clear);

            filter1.setPriority(Integer.MAX_VALUE);
            context.registerReceiver(myReceiver1, filter1);

        } catch (Exception e) {

        }
    }
    private BroadcastReceiver myReceiver1 = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();


                if(action.equals(ReceiverMsg.message)){

                    getData();

                }

            } catch (Exception e) {

                System.out.println("e"+e.toString());
            }

        }

    };

    private Handler mHandler = new Handler() {

        @SuppressLint("HandlerLeak")
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:


                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        String status = jsonObject.getString("status");
                        if (status.equals("200")) {
                            llqr.setVisibility(View.VISIBLE);
                            code = jsonObject.getString("data");
                            SharedPreferences.Editor editor = sp.edit();
                            editor.putString("code", code);
                            txtcode.setText("设备编号:" +code);
                            editor.commit();


                            start();


                            Glide.with(context).load(API.http + "/qr?text=" + code).into(qr);





                        }
                    } catch (Exception e) {

                        Toast.makeText(MainActivity.this, "mHandler1" + e.toString(), Toast.LENGTH_LONG).show();
                    }


                    break;
                case 2:

                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        String status = jsonObject.getString("status");
                        if (status.equals("200")) {
                            JSONArray jsonArray = jsonObject.getJSONArray("data");

                            String checkstr = jsonObject.getString("data");
                            if(checkstr.equals("")||checkstr.equals("[]")){
                                intentImage=null;
                                intentVideo=null;
                                Intent intent = new Intent();
                                intent.setAction(ReceiverMsg.close);
                                sendBroadcast(intent);
                                return;
                            }

                            String str = "";
                            for (int i = 0; i < jsonArray.length(); i++) {
                                str += jsonArray.getString(i) + ",";
                            }
                            imgurl = str;

                            if (intentImage == null) {
                                intentImage = new Intent(MainActivity.this, ImageActivity.class);
                                intentImage.putExtra("url", imgurl);
                                startActivity(intentImage);
                            } else {

                                Intent intent = new Intent();
                                intent.setAction(ReceiverMsg.close);
                                sendBroadcast(intent);


                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        // 延迟1秒后执行的代码

                                        intentImage = new Intent(MainActivity.this, ImageActivity.class);
                                        intentImage.putExtra("url", imgurl);
                                        startActivity(intentImage);

                                    }
                                }, 500);


                            }


                        }





                    }catch (Exception ee){
                        Toast.makeText(MainActivity.this,"mHandler2"+ee.toString(),Toast.LENGTH_LONG).show();
                    }

                    break;


            }
        }
    };

    private void  getData(){
        Date startTime = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(startTime);
        int year = c.get(java.util.Calendar.YEAR);
        int month = c.get(java.util.Calendar.MONTH) + 1;//获取月份（因为在格里高利历和罗马儒略历一年中第一个月为JANUARY，它为0，最后一个月取决于一年中的月份数，所以这个值初始为0，所以需要加1）
        int day = c.get(java.util.Calendar.DATE);

        String monthstr="";
        String daystr="";
        if(month<10){
            monthstr="0"+month;
        }
        if(day<10){
            daystr="0"+day;
        }
        String date =year+"-"+monthstr+"-"+daystr;




        String timestamp = Utils.timestamp()+"";
        String sign =  Utils.md5(Utils.md5(Utils.md5(keys)+Utils.md5(timestamp)));

       // code="1bcfff15724f4521";


        String url ="http://penguakeji.com/apis/sync?code="+code+"&date="+date+"&sign="+sign+"&_="+timestamp;
        IndexService.getData(mHandler,url,2);
    }
    private  void  start(){


        getData();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if(myReceiver1!=null){
            unregisterReceiver(myReceiver1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==2){
            initData();
        }
    }
}
